<?php

declare(strict_types=1);

namespace Tool\Command;

use Marx\Console\Color;
use Marx\Console\Command\AbstractCommand;

/**
 * 转义工具.
 */
class DecodeCommand extends AbstractCommand
{
    public function __construct()
    {
        $this->setName('decode');
        $this->setDesc('php decode tool');
        $this->addOption('ascii', 'a', false, 'decode ASCII to UTF-8');
        $this->addOption('unicode', 'u', false, 'decode UNICODE to UTF-8');
    }

    public function execute(): void
    {
        $method = $this->getMethod();
        if (!$method) {
            $this->output->write('input method error!');

            return;
        }

        while (true) {
            $this->output->askQuestion(Color::yellow('input words,or empty string to exit'));
            $input = $this->input->readAnswer();
            if ('' === $input) {
                $this->output->write('bye!');

                break;
            }

            $this->output->write(Color::green($this->{$method}($input)));
        }
    }

    private function getMethod(): string
    {
        if (!is_null($this->input->getOption('ascii'))) {
            return 'ascii';
        }

        if (!is_null($this->input->getOption('unicode'))) {
            return 'unicode';
        }

        return '';
    }

    private function ascii(string $input): string
    {
        return urldecode(str_replace('\x', '%', $input)) ?? '';
    }

    private function unicode(string $input): string
    {
        return json_decode('["'.str_replace('%', '\u', $input).'"]')[0] ?? '';
    }
}
